<?php


namespace app\astrologer\controller\v5;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\cachemodel\ZlcrAstrAccountRecord;
use app\common\lib\Util;
use app\common\model\User;
use app\zyhsapi\model\ZyhsUser;
use think\Db;

class Earnings extends AstrAuth
{
    /**
     * 获取列表数据
     * @method GET
     */
    public function list()
    {
        $param['page'] = $this->request->param('page/d', 1);
        $param['limit'] = $this->request->param('limit/d', 10);
        //h5
        $param['start_time'] = $this->request->param('start_time/s', 0);
        $param['end_time'] = $this->request->param('end_time/s', 0);
        //pc
        $rangeTime = input('range_time/a', []);
        $isTeam = input('is_team/d', 0);
        $param['question'] = $this->request->param('question/s', '');
        $param['qtype'] = $this->request->only(['qtype']);
        $param['status'] = $this->request->only(['status']);
        $questionType = input('question_type/d', 0); // 0=>不筛选 1=>定制报告 2=>问答

        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($this->astrInfo['id'], ['balance', 'total_amount']);
        $teamId = $this->astrInfo['team_id'] ?? 0;
        if ($isTeam === 1 && !$teamId)
        {
            return show(config('code.error'), '服务异常，请稍后再试');
        }

        if ($questionType === 1)
        {   // 定制报告
            $where = [];
            if ($isTeam === 1)
            {
                $where['a.team_id'] = $teamId;
            } else
            {
                $where['a.team_id'] = 0;
            }
            if (!empty($rangeTime))
            {
                if (!empty($rangeTime[0]) && !empty($rangeTime[1]))
                {
                    // 前端组件，肯定有这两个参数
                    $where['a.create_time'] = ['between', [strtotime($rangeTime[0]), strtotime($rangeTime[1])]];
                }
            } else if (($param['start_time'] && $param['end_time']))
            {
                $start_time = strtotime($param['start_time']);
                $end_time = strtotime($param['end_time']);
                if ($end_time < $start_time)
                {
                    return show(0, '开始时间不能大于结束时间！');
                } else
                {
                    $where['a.create_time'] = ['between', [$start_time, $end_time]];
                }

            } else if ($param['start_time'])
            {
                $start_time = strtotime($param['start_time']);
                $where['a.create_time'] = ['>=', $start_time];
            } else if ($param['end_time'])
            {
                $where['a.create_time'] = ['<', strtotime($param['start_time'])];
            }

            $where['q.astr_id'] = $this->astrInfo['id'];
            if ($param['qtype'])
            {
                foreach ($param['qtype']['qtype'] as $k => $v)
                {
                    $qtype['qtype']['qtype'][$k] = (int)$v;
                }
                $where['q.qtype'] = ['in', $qtype['qtype']['qtype']];
            }

            if ($param['status'])
            {
                if (is_array($param['status']['status']))
                {
                    foreach ($param['status']['status'] as $k => $v)
                    {
                        $param['status']['status'][$k] = (int)$v;
                    }
                    if ($param['status']['status'][0] === 5)
                    {//如果是已完成，那么把评价待审核和已评价也加上
                        $param['status']['status'][] = 6;
                        $param['status']['status'][] = 7;
                    }
                    $where['q.status'] = ['in', $param['status']['status']];
                } else
                {
                    $status = [];
                    foreach ($param['status'] as $k => $v)
                    {
                        $status[] = (int)$v;
                    }
                    if ($status[0] === 5)
                    {//如果是已完成，那么把评价待审核和已评价也加上
                        $status[] = 6;
                        $status[] = 7;
                    }
                    $where['q.status'] = ['in', $status];
                }

            }

            if ($param['question'])
            {
                $where['q.question_name'] = ['like', '%' . $param['question'] . '%'];
            }

            $resData = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->alias('q')
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
                ->where($where)->order('a.create_time desc')
                ->field('q.id qid,q.question_name question,q.astr_receiving_time,a.amount earnings,q.status,q.qtype,q.is_merge,q.is_back,q.check_time1,q.check_time2,q.answer_time,a.proportion,q.invalid_time,a.type zlcr_astr_account_record_type,a.create_time')
                ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

            $dataList = [];
            foreach ($resData['data'] as $key => $datum)
            {
                // 定制报告
                $dataList[] = [
                    'task_id' => $datum['qid'],
                    'qid' => $datum['qid'],
                    'question_type' => 4,
                    'question' => $datum['question'],
                    'astr_receiving_time' => $datum['astr_receiving_time'],
                    'create_time' => $datum['create_time'],
                    'earnings' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? 0 : $datum['earnings'],
                    'status_des' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? '未完成' : '完成任务',
                    'status_color' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? '#FFB500' : '#00D8D3',
                    'proportion' => $datum['proportion'],
                    'is_merge' => $datum['is_merge'] ?? '',
                    'qtype' => $datum['qtype'],
                    'answer_time' => $datum['answer_time'],
                    'check_time2' => $datum['check_time2'],
                    'app_type' => 1,
                ];
            }
        } else
        {
            $where = [];
            if ($isTeam === 1)
            {
                $where['team_id'] = $teamId;
            } else
            {
                $where['team_id'] = 0;
            }
            if (!empty($rangeTime))
            {
                if (!empty($rangeTime[0]) && !empty($rangeTime[1]))
                {
                    // 前端组件，肯定有这两个参数
                    $where['create_time'] = ['between', [strtotime($rangeTime[0]), strtotime($rangeTime[1])]];
                }
            } else if (($param['start_time'] && $param['end_time']))
            {
                $start_time = strtotime($param['start_time']);
                $end_time = strtotime($param['end_time']);
                if ($end_time < $start_time)
                {
                    return show(0, '开始时间不能大于结束时间！');
                } else
                {
                    $where['create_time'] = ['between', [$start_time, $end_time]];
                }

            } else if ($param['start_time'])
            {
                $start_time = strtotime($param['start_time']);
                $where['create_time'] = ['>=', $start_time];
            } else if ($param['end_time'])
            {
                $where['create_time'] = ['<', strtotime($param['start_time'])];
            }
            if ($questionType > 0)
            {
                if ($questionType === 2)
                {
                    $where['question_type'] = ['in', [2, 4]];
                } else
                {
                    $where['question_type'] = $questionType;
                }
            }
            $astrId = $this->astrInfo['id'];
            $resData = (new ZlcrAstrAccountRecord())->where($where)->where(['astr_id' => $astrId, 'type' => ['in', [1, 4, 5]]])->order('create_time desc')
                ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

            $qidData = [];
            foreach ($resData['data'] as $key => $datum)
            {
                switch ($datum['question_type'])
                {
                    case 1:
                    case 2:
                    case 4:
                        $qidData[$datum['question_type']][] = $datum['qid'];
                        break;
                    case 3:
                    case 5:
                        $qidData[3][] = $datum['gid'];
                        break;
                    case 6: //  准了-连线咨询 打赏
                        $qidData[6][] = $datum['gid'];
                        break;
                    case 7: //  准有好事-连线咨询 打赏
                        $qidData[7][] = $datum['gid'];
                        break;
                }
            }
            // 1=>定制报告 2=>问答 3=>连线咨询 4=>准有好事-问答
            $questionInfo1 = [];
            if (isset($qidData[1]) && $qidData[1])
            {
                $questionInfo1 = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->where(['id' => ['in', $qidData[1]]])->column('question_name,astr_receiving_time,is_merge,qtype,answer_time,check_time2', 'id');
            }
            $questionInfo2 = [];
            if (isset($qidData[2]) && $qidData[2])
            {   // 问答
                $questionInfo2 = Db::table('wechat_backup_07_18_14_43_00.zlcr2_user_question')->where(['id' => ['in', $qidData[2]]])->column('*', 'id');
            }
            $questionInfo3 = [];
            if (isset($qidData[3]) && $qidData[3])
            {   // 连线咨询
                $questionInfo3 = Db::table('good_wechat.zyhs_consult_chat_rtc_record')->where(['id' => ['in', $qidData[3]]])->column('*', 'id');
            }
            $questionInfo4 = [];
            if (isset($qidData[4]) && $qidData[4])
            {   // 准有好事 - 问答
                $questionInfo4 = Db::table('good_wechat.zyhs_astr_tasks')->alias('t')
                    ->join('good_wechat.zyhs_user_question q', 'q.id=t.qid')->where(['t.id' => ['in', $qidData[4]]])->column('q.question,q.id qid,q.question_type,t.create_time astr_receiving_time,q.is_synastry,t.status,t.lock_reason', 't.id');
            }
            $questionInfo6 = [];
            if (isset($qidData[6]) && $qidData[6])
            {   // 准了-连线咨询 打赏
                $questionInfo6 = Db::table('wechat_backup_07_18_14_43_00.zhunle_user_account_record')->where(['id' => ['in', $qidData[6]]])->column('*', 'id');
            }
            $questionInfo7 = [];
            if (isset($qidData[7]) && $qidData[7])
            {   // 准有好事-连线咨询 打赏
                $questionInfo7 = Db::table('good_wechat.zyhs_user_account_record')->where(['id' => ['in', $qidData[7]]])->column('*', 'id');
            }

            $dataList = [];
            $userInfoList = [];
            $zyhsUserInfoList = [];
            foreach ($resData['data'] as $key => $datum)
            {
                $itemInfo = null;
                switch ($datum['question_type'])
                {
                    case 1:
                        $itemInfo = $questionInfo1[$datum['qid']] ?? null;
                        break;
                    case 2:
                        $itemInfo = $questionInfo2[$datum['qid']] ?? null;
                        break;
                    case 3:
                    case 5:
                        $itemInfo = $questionInfo3[$datum['gid']] ?? null;
                        break;
                    case 4:
                        $itemInfo = $questionInfo4[$datum['qid']] ?? null;
                        break;
                    case 6: // 准了-连线咨询 打赏
                        $itemInfo = $questionInfo6[$datum['gid']] ?? null;
                        $itemInfo['extend'] = json_decode($itemInfo['extend'], true);
                        break;
                    case 7: // 准有好事-连线咨询 打赏
                        $itemInfo = $questionInfo7[$datum['gid']] ?? null;
                        break;
                }
                if (!$itemInfo)
                {
                    continue;
                }

                switch ($datum['question_type'])
                {
                    case 1: // 准了 - 定制报告
                        $dataList[] = [
                            'task_id' => (string)$datum['qid'],
                            'qid' => (string)$datum['qid'],
                            'question_type' => 4,
                            'question' => $itemInfo['question_name'],
                            'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => '完成任务',
                            'status_color' => '#00D8D3',
                            'proportion' => $datum['proportion'],
                            'is_merge' => (int)($itemInfo['is_merge'] ?? 0),
                            'qtype' => $itemInfo['qtype'],
                            'answer_time' => $itemInfo['answer_time'],
                            'check_time2' => $itemInfo['check_time2'],
                            'app_type' => 1,
                        ];
                        break;
                    case 2: // 准了 - 问答
                        $dataList[] = [
                            'task_id' => (string)Db::table('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks')->where(['astr_id' => $this->astrInfo['id'], 'qid' => $datum['qid']])->value('id'),
                            'qid' => (string)$datum['qid'],
                            'question_type' => (int)$itemInfo['question_type'],
                            'question' => $itemInfo['question'],
                            'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => $itemInfo['lock_reason'] ? '扣除收益：' . $itemInfo['lock_reason'] : '完成任务',
                            'status_color' => $itemInfo['lock_reason'] ? '#FFB500' : '#00D8D3',
                            'proportion' => $datum['proportion'],
                            'is_merge' => (int)($itemInfo['is_synastry'] ?? 0),
                            'qtype' => 0,
                            'answer_time' => 0,
                            'check_time2' => 0,
                            'app_type' => 1,
                        ];
                        break;
                    case 3: // 准有好事 - 连线咨询
                    case 5: // 准了 - 连线咨询
                        $appType = (int)($itemInfo['app_type'] ?? 1); // 1=>准有好事  2=>准了APP
                        $dataList[] = [
                            'task_id' => (string)$itemInfo['chat_detail_id'],
                            'qid' => (string)$itemInfo['chat_detail_id'],
                            'question_type' => 5,
                            'question' => '计价时长：' . (Util::secondToMinute($itemInfo['eff_duration'])) . '(单价：' . ($itemInfo['unit_price'] / 10 * $datum['proportion']) . "元/分钟)",
                            'astr_receiving_time' => '',
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => (int)$datum['status'] === 1 ? '完成任务' : '操作纠正，收益扣除',
                            'status_color' => '#00D8D3',
                            'proportion' => $datum['proportion'],
                            'is_merge' => 0,
                            'qtype' => 0,
                            'answer_time' => 0,
                            'check_time2' => 0,
                            'app_type' => $appType === 1 ? 2 : 1,   // 1=>准了 2=>准有好事
                        ];
                        break;
                    case 4: // 准有好事 - 问答
                        $statusDes = '完成任务';
                        $statusColor = '#00D8D3';
                        if ($datum['type'] == 4)
                        {
                            $statusDes = '扣除收益';
                            if ($itemInfo['lock_reason'])
                            {
                                $statusDes .= '：' . $itemInfo['lock_reason'];
                            }
                            $statusColor = '#FFB500';

                            $datum['amount'] = '-' . $datum['amount'];
                        }
                        if ($datum['type'] == 5)
                        {
                            $statusDes = '完成任务';
                        }

                        $dataList[] = [
                            'task_id' => (string)$itemInfo['id'],
                            'qid' => (string)$itemInfo['qid'],
                            'question_type' => (int)$itemInfo['question_type'], //  1=>问答星盘 2=>问答骰子 3=>问答塔罗 4=>定制报告 5=>连线咨询 6=>连线咨询打赏
                            'question' => $itemInfo['question'],
                            'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => $statusDes,
                            'status_color' => $statusColor,
                            'proportion' => $datum['proportion'],
                            'is_merge' => (int)($itemInfo['is_synastry'] ?? 0),
                            'qtype' => 0,
                            'answer_time' => 0,
                            'check_time2' => 0,
                            'app_type' => 2,
                        ];
                        break;
                    case 6: // 准了-连线咨询 打赏
                        if (isset($userInfoList[$itemInfo['uid']]))
                        {
                            $nickname = $userInfoList[$itemInfo['uid']]['nickname'];
                        } else
                        {
                            $userInfo = (new User())->getUserinfo(['id' => $itemInfo['uid']]);
                            $nickname = $userInfo['nickname'];
                            $userInfoList[$itemInfo['uid']] = [
                                'nickname' => $nickname,
                            ];
                        }
                        $dataList[] = [
                            'task_id' => $nickname,
                            'qid' => '',
                            'question_type' => 6, //  1=>问答星盘 2=>问答骰子 3=>问答塔罗 4=>定制报告 5=>连线咨询 6=>连线咨询打赏
                            'question' => sprintf("%sx%d", $itemInfo['extend']['gift_name'], $itemInfo['extend']['num']),
                            'astr_receiving_time' => 0,
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => '',
                            'status_color' => '',
                            'proportion' => $datum['proportion'],
                            'is_merge' => 0,
                            'qtype' => 0,
                            'answer_time' => 0,
                            'check_time2' => 0,
                            'app_type' => 1,
                        ];
                        break;
                    case 7: // 准有好事-连线咨询 打赏
                        if (isset($zyhsUserInfoList[$itemInfo['uid']]))
                        {
                            $nickname = $zyhsUserInfoList[$itemInfo['uid']]['nickname'];
                        } else
                        {
                            $userInfo = (new ZyhsUser())->getInfoById($itemInfo['uid']);
                            $nickname = $userInfo['nickname'];
                            $zyhsUserInfoList[$itemInfo['uid']] = [
                                'nickname' => $nickname,
                            ];
                        }
                        $dataList[] = [
                            'task_id' => $nickname,
                            'qid' => '',
                            'question_type' => 6, //  1=>问答星盘 2=>问答骰子 3=>问答塔罗 4=>定制报告 5=>连线咨询 6=>连线咨询打赏
                            'question' => sprintf("%sx%d", $itemInfo['extend']['gift_name'], $itemInfo['extend']['num']),
                            'astr_receiving_time' => 0,
                            'create_time' => (int)$datum['create_time'],
                            'earnings' => $datum['amount'],
                            'status_des' => '',
                            'status_color' => '',
                            'proportion' => $datum['proportion'],
                            'is_merge' => 0,
                            'qtype' => 0,
                            'answer_time' => 0,
                            'check_time2' => 0,
                            'app_type' => 2,
                        ];
                        break;
                }
            }
        }
        // 计算团队 至今总收益 以及 未提现金额
        if ($teamId)
        {   // 团队 占星师个人 总收益
            $teamTotalAmount = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'status' => 1, 'team_id' => $teamId])->sum('amount');
            // 团队 占星师个人 未提现总余额
            $teamBalance = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => ['in', [1, 5]], 'team_id' => $teamId, 'status' => 1, 'is_withdrawal' => 0])->sum('amount');
            // 团队 占星师个人 冻结收益
            $teamBalanceFrozen = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 4, 'team_id' => $teamId, 'status' => 1, 'is_withdrawal' => 0])->sum('amount');
            // 团队未结算金额 - 团队冻结金额
            $teamBalance = $teamBalance - $teamBalanceFrozen;
        } else
        {
            $teamTotalAmount = 0;
            $teamBalance = 0;
        }

        if ($isTeam === 1)
        {   // 未结算
            $balance = $teamBalance;
            $totalAmount = $teamTotalAmount;
        } else
        {
            $balance = $accountInfo['balance'] - $teamBalance; // 当前余额 -  =  个人余额（个人未结算金额）
            $totalAmount = $accountInfo['total_amount'] - $teamTotalAmount; // 当前总收益 - 团队个人总收益 = 个人结算中总收益
        }

        $resData['data'] = $dataList;
        $resData['balance'] = (string)$balance;
        $resData['earn_all'] = (string)$totalAmount;
        $resData['is_team'] = $teamId > 0 ? 1 : 0;

        return show(200, '请求成功', $resData);
    }
}
